<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-select
            v-model="listQuery.name"
            placeholder="选择人员"
            size="small"
            clearable
          >
            <el-option
              v-for="item in employees"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            size="small"
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="listQuery.flag"
            placeholder="支付标识"
            size="small"
            clearable
          >
            <el-option label="未支付" :value="false"></el-option>
            <el-option label="已支付" :value="true"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="付款单" name="payment">
          <el-form
            :inline="true"
            :model="payInfo"
            :rules="payRules"
            ref="payRef"
          >
            <el-form-item label="账号" prop="account_type">
              <el-select
                v-model="payInfo.account_type"
                placeholder="付款账号"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in payBanks"
                  :label="item.account"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="科目" prop="acc_title">
              <el-cascader
                v-model="selPayKeys"
                :options="accountList"
                :props="props"
                @change="handleTitleChange"
                clearable
                size="small"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="时间" prop="order_time">
              <el-date-picker
                v-model="payInfo.order_time"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="small"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button
                type="success"
                icon="el-icon-plus"
                size="mini"
                @click="handleAccount"
                :disabled="btnEnabled"
                >结算</el-button
              >
            </el-form-item>
          </el-form>

          <el-table
            ref="table"
            :data="payList"
            border
            size="small"
            v-loading="listLoading"
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
            show-summary
            :summary-method="getSummaries"
          >
            <el-table-column type="selection" align="center"> </el-table-column>
            <el-table-column
              v-for="item in tableColumns"
              :key="item.key"
              align="center"
              :label="item.title"
              :prop="item.key"
            >
              <template slot-scope="scope">
                <span v-if="item.key == 'flag'">
                  <el-switch
                    v-model="scope.row[item.key]"
                    :disabled="scope.row.flag_ok === true"
                  ></el-switch>
                </span>
                <span v-else-if="item.key == 'money'">
                  {{ scope.row[item.key].toFixed(2) }}
                </span>
                <span v-else>
                  {{ scope.row[item.key] }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="180px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleEdit(scope)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleDelete(scope)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.page_size"
            @pagination="getPayList"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="60%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 20px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="单号"
              prop="order_no"
              v-if="dialogType === 'edit'"
            >
              <el-input
                type="text"
                v-model="form.order_no"
                placeholder="单号"
                maxlength="24"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开单时间" prop="order_time">
              <el-date-picker
                v-model="form.order_time"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择开单时间"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售单" prop="sale_order">
              <el-select
                v-model="form.sale_order"
                placeholder="选择销售单"
                clearable
                @change="selectChange"
                :disabled="dialogType === 'edit'"
              >
                <el-option
                  v-for="item in sales"
                  :key="item.id"
                  :label="item.order_no + '[' + item.customer_name + ']'"
                  :value="item.id"
                >
                  <span style="float: left"
                    >{{ item.order_no }}[{{ item.customer_name }}]</span
                  >
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.case_name
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="person">
              <el-select v-model="form.person" placeholder="姓名">
                <el-option
                  v-for="item in employees"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科目" prop="acc_title">
              <el-cascader
                v-model="selectedKeys"
                :options="accountList"
                :props="props"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="支付账号" prop="account_type">
              <el-select
                v-model="form.account_type"
                placeholder="支付账号"
                clearable
              >
                <el-option
                  v-for="item in banks"
                  :key="item.id"
                  :label="item.account"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="money">
              <el-input v-model="form.money" placeholder="金额" clearable>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="付款确认" prop="flag">
              <el-radio-group v-model="form.flag">
                <el-radio :label="true">确定</el-radio>
                <el-radio :label="false">暂不</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.desc" placeholder="备注" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经手人" v-if="form.user_name">
              <el-input
                v-model="form.user_name"
                placeholder="经手人"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="HandleSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getParentsPath } from "@/utils/index";
import { getCurrentDate } from "@/utils/datetime";
import {
  getSaleList,
  getPayList,
  addPay,
  updatePay,
  delPay,
  updatePays,
} from "@/api/sale";
import { getEmployeeList } from "@/api/employee";
import { get_account_titles } from "@/api/account";
import { getBanks } from "@/api/bank";
import { positions, pickerOptions } from "@/utils/const";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  order_no: "",
  order_time: getCurrentDate(),
  sale_order: null,
  person: null,
  acc_title: null,
  account_type: null,
  money: 0,
  flag: false,
  desc: "",
  user: null,
};

export default {
  name: "Pay",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };

    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        sale_order: [
          { required: true, message: "请选择销售单号", trigger: "blur" },
        ],
        order_time: [
          { required: true, message: "请输入开单时间", trigger: "blur" },
        ],
        acc_title: [
          { required: true, message: "请选择会计科目", trigger: "blur" },
        ],
        account_type: [
          { required: true, message: "请选择付款账户", trigger: "blur" },
        ],
        money: [{ validator: checkMoney, trigger: "blur" }],
      },

      payInfo: {
        account_type: null,
        acc_title: null,
        order_time: getCurrentDate(),
      },

      payRules: {
        order_time: [
          { required: true, message: "请输入结算时间", trigger: "blur" },
        ],
        acc_title: [
          { required: true, message: "请选择会计科目", trigger: "blur" },
        ],
        account_type: [
          { required: true, message: "请选择付款账户", trigger: "blur" },
        ],
      },

      title: "付款单",
      activeName: "payment",

      accountList: [],
      employees: [],
      sales: [],
      banks: [],
      payBanks: [],
      selectedKeys: [],
      selPayKeys: [],
      positions,
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      dialogVisible: false,
      dialogType: "new",
      payList: [],
      selections: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
        search_date: "",
        flag: false,
      },
      listCondition: {
        page: 1,
        page_size: 20,
        name: undefined,
        search_date: "",
      },

      tableColumns: [
        {
          key: "order_no",
          title: "单号",
        },
        {
          key: "person_name",
          title: "姓名",
        },
        {
          key: "order_time",
          title: "时间",
        },
        {
          key: "customer_name",
          title: "客户",
        },
        {
          key: "acc_type_name",
          title: "付款账号",
        },
        {
          key: "account_name",
          title: "科目",
        },
        {
          key: "money",
          title: "金额(元)",
        },
        {
          key: "flag",
          title: "付款确认",
        },
      ],

      pickerOptions,
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
    btnEnabled() {
      const items = this.selections.filter(
        (item) => item.flag === true && item.flag_ok === false
      );
      if (
        items.length == this.selections.length &&
        this.selections.length > 0
      ) {
        return false;
      }
      return true;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getPayList();
    this.getAccounts();
    this.getEmployeeList();
    this.getSales();
    this.getBankList();
  },
  methods: {
    // 支付单据
    getPayList() {
      this.listLoading = true;
      getPayList(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.payList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },

    getEmployeeList() {
      getEmployeeList().then((res) => {
        this.employees = res;
      });
    },
    getSales() {
      const query = {};
      getSaleList(query)
        .then((res) => {
          this.sales = res;
        })
        .catch((error) => {
          this.$message.error("获取销售单数据失败");
        });
    },
    getAccounts() {
      get_account_titles({}).then((res) => {
        this.accountList = res;
      });
    },
    getBankList() {
      getBanks().then((res) => {
        this.banks = res;
        this.payBanks = this.banks.filter((item) => item.id != 1);
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }

        if (column.property === "money") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
          return;
        } else {
          return;
        }
      });
      return sums;
    },

    dataFormatter(row, column, cellValue, index) {
      console.log("format:", column);
      if (column.property == "money") {
        return cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getPayList();
    },

    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(
          this.form.acc_title,
          this.accountList
        );
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delPay(row.id);

          this.payList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async HandleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updatePay(this.form);
          const index = this.payList.findIndex((v) => v.id === res.id);
          this.payList.splice(index, 1, res);
        } else {
          this.form.user = this.uid;
          res = await addPay(this.form);
          const { id } = res;
          if (id > 0) {
            this.getPayList();
            this.getSales();
          }
        }

        const { order_no, person_name, money } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>单号: ${order_no}</div>
              <div>姓名: ${person_name}</div>
              <div>付款金额: ${money}</div>
            `,
          type: "success",
        });
      });
    },
    handleChange(value) {
      if (this.selectedKeys.length > 0) {
        this.form.acc_title = this.selectedKeys[this.selectedKeys.length - 1];
      } else {
        this.form.acc_title = undefined;
      }
    },
    handleTitleChange(value) {
      console.log(value);
      if (this.selPayKeys.length > 0) {
        this.payInfo.acc_title = this.selPayKeys[this.selPayKeys.length - 1];
      } else {
        this.payInfo.acc_title = null;
      }
    },
    selectChange(value) {
      if (!value) {
        return;
      }
      const sale = this.sales.find((v) => v.id == value);
      this.form.customer_name = sale.customer_name;
    },
    handleSelectionChange(val) {
      this.selections = val;
      // this.setPayInfo();
      // console.log(this.selections);
    },
    setPayInfo() {
      this.selections.map((item) => {
        item.acc_title = this.payInfo.acc_title;
        item.account_type = this.payInfo.account_type;
        item.order_time = this.payInfo.order_time;
        item.user = this.uid;
      });
    },
    isPayFlag() {
      ///去掉已经结算的数据
      this.selections.forEach((item, index) => {
        if (item.flag_ok === true) {
          this.$refs.table.toggleRowSelection(item, false);
        }
      });
      if (this.selections.length == 0) {
        this.$message.warning("请选择未结算单号");
        return false;
      }

      const sels = this.selections.filter((item) => {
        if (item.flag == false && item.flag_ok == false) {
          return item;
        }
      });
      if (sels.length === 0) return true;

      const orders = sels.map((item) => {
        return item.order_no;
      });
      console.log("orders:", orders);
      this.$message.warning(orders.toString() + "未设置支付确认");
      return false;
    },
    async handleAccount() {
      this.$refs.payRef.validate(async (valid) => {
        if (!valid) return;
        console.log(this.selections);

        if (!this.isPayFlag()) return;

        this.setPayInfo();

        try {
          const res = await updatePays(this.selections);
          console.log(res);
          if (res) {
            this.getPayList();
            this.$notify({
              title: "Success",
              dangerouslyUseHTMLString: true,
              message: "结算成功!",
              type: "success",
            });
          }
        } catch (error) {
          console.log(error);
          this.$message.warning("结算失败！");
        }
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-form--inline .el-form-item {
    margin-bottom: 10px;
  }
}
</style>